$(function () {
    // 初始化代码高亮
    hljs.highlightAll();

    $("#comment-btn").on("click", function (event) {
        event.preventDefault();
        let $this = $(this);

        let user_id = $this.attr("data-user-id");
        if (!user_id || user_id === "") {
            window.location = "/login/";
            return;
        }

        let content = $("#comment-textarea").val();
        var post_id = $this.attr("data-post-id");

        csrf_ajax.post({
            url: "/comment/",
            data: {content, post_id},
            success: function (result) {
                if (result['code'] === 200) {
                    window.location.reload();
                } else {
                    alert(result['message']);
                }
            }
        })
    });
});


$(document).ready(function () {
    // 页面加载时记录初始点赞状态
    let initialLiked = $('#like').hasClass('liked');
    let isLiked = initialLiked;
    let likeDebounceTimer = null;

    console.log("初始状态 - initialLiked:", initialLiked, "isLiked:", isLiked);

    // 点赞功能
    $('#like').on('click', function (event) {
        event.preventDefault();
        let userId = $('#like-container').data('user-id');
        if (!userId || userId === "") {
            window.location = "/login/";
            return;
        }

        var $icon = $(this);

        // 切换点赞状态（本地）
        if ($icon.hasClass('liked')) {
            $icon.removeClass('liked');
            isLiked = false;
            // 减少点赞数
            var $countElement = $icon.siblings('.like-count');
            var currentCount = parseInt($countElement.text()) || 0;
            if (currentCount > 0) {
                $countElement.text(currentCount - 1);
            }
        } else {
            $icon.addClass('liked');
            isLiked = true;
            // 增加点赞数
            $countElement = $icon.siblings('.like-count');
            currentCount = parseInt($countElement.text()) || 0;
            $countElement.text(currentCount + 1);
        }

        // 添加调试信息
        console.log("点击后 - initialLiked:", initialLiked, "isLiked:", isLiked);
        console.log("是否应该发送请求:", isLiked !== initialLiked);

        // 防抖处理：延迟500ms发送请求
        clearTimeout(likeDebounceTimer);
        likeDebounceTimer = setTimeout(function () {
            console.log("setTimeout函数执行了");
            if (isLiked !== initialLiked) {
                console.log("发送请求");
                sendLikeStatusToServer(isLiked);
            }
        }, 500);
    });

    // 发送点赞状态到服务器的函数
    function sendLikeStatusToServer(liked) {
        console.log("发送点赞状态到服务端");
        let postId = $('#like-container').data('post-id');
        let userId = $('#like-container').data('user-id');

        console.log("postId:", postId, "userId:", userId);


        if (postId && userId) {
            // 发送请求前更新初始状态，避免重复发送
            initialLiked = isLiked;

            csrf_ajax.post({
                url: '/post/like/',
                data: {
                    post_id: postId,
                    user_id: userId,
                    like_status: liked ? 1 : 0
                },
                success: function (result) {
                    if (result['code'] === 200) {
                        console.log("点赞状态更新成功");
                    } else {
                        alert(result['message']);
                    }
                },
            });
        }
    }
});

